package com.example.yls.demoa;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.view.View;
import android.webkit.WebView;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import java.util.List;

import cn.bmob.v3.BmobQuery;
import cn.bmob.v3.BmobUser;
import cn.bmob.v3.exception.BmobException;
import cn.bmob.v3.listener.FindListener;
import cn.bmob.v3.listener.SaveListener;
import cn.bmob.v3.listener.UpdateListener;

public class ViewNewsActivity extends AppCompatActivity {
    private Toolbar mToolbar;
    private DrawerLayout mDrawerLayout;
    private String newsUrl;
    private String newsID; //通过intent传进来
    private WebView webView;
    private EditText edtComment;
    private Button btnComment;
    private Button btnCollect;
    private boolean isCollect =  false;
    private RecyclerView recyclerView;

    private CommentAdapter adapter;
    private List<Comment> mComments;
    private Handler handler;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_view_news);


        initCommentViews();
        initCollectButton();
        updateCollectState();
        getComment();



        newsUrl = getIntent().getStringExtra("NEWS_URL");
        newsID = getIntent().getStringExtra("NEWS_ID");

        webView = findViewById(R.id.wv_news);
        webView.loadUrl(newsUrl);

        mToolbar = findViewById(R.id.toolbar);
//        setSupportActionBar(mToolbar);
        mDrawerLayout = findViewById(R.id.drawerlayout);

        ActionBarDrawerToggle drawerToggle = new ActionBarDrawerToggle(this,mDrawerLayout,mToolbar,R.string.open,R.string.close){
            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
            }
        };
        drawerToggle.syncState();
        mDrawerLayout.setDrawerListener(drawerToggle);

        initHandler();
        initRecyclerView();

    }

    private void getComment() {
        if(BmobUser.getCurrentUser() == null){
            return;
        }
        BmobQuery<Comment> query = new BmobQuery<>();
        query.addWhereEqualTo("new_id", newsID);
        query.findObjects(new FindListener<Comment>() {
            @Override
            public void done(List<Comment> list, BmobException e) {
                if(mComments == null){
                    mComments = list;
                }
                handler.sendEmptyMessage(1001);
                Log.e("TAG",mComments.get(0).getUser_id()+"");
            }
        });
    }

    private void initRecyclerView() {
        recyclerView = findViewById(R.id.rv_comment);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        recyclerView.setLayoutManager(linearLayoutManager);
        adapter = new CommentAdapter(this,mComments);
        recyclerView.setAdapter(adapter);
    }

    private void updateCollectState() {
        if(BmobUser.getCurrentUser() == null){
            return;
        }

        String userID = BmobUser.getCurrentUser().getObjectId();
        BmobQuery<Collect> query = new BmobQuery<>();
        query.addWhereEqualTo("new_id", newsID);
        query.addWhereEqualTo("user_id", userID);
        query.findObjects(new FindListener<Collect>() {
            @Override
            public void done(List<Collect> list, BmobException e) {
                if(list != null && list.size() > 0){
                    isCollect = list.get(0).getIs_collect();
                    if(isCollect){
                        btnCollect.setText("取消收藏");
                    }else{
                        btnCollect.setText("收藏");
                    }
                }
            }
        });

    }

    private void initCollectButton() {
        btnCollect = findViewById(R.id.btn_collect);
        btnCollect.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(BmobUser.getCurrentUser() == null){
                    Intent intent = new Intent();
                    intent.setClass(ViewNewsActivity.this, LoginActivity.class);
                    startActivity(intent);
                }

                final String userID = BmobUser.getCurrentUser().getObjectId();
                BmobQuery<Collect> query = new BmobQuery<>();
                query.addWhereEqualTo("new_id", newsID);
                query.addWhereEqualTo("user_id", userID);
                query.findObjects(new FindListener<Collect>() {
                    @Override
                    public void done(List<Collect> list, BmobException e) {
                        if(list != null && list.size() > 0){
                            // 如果找到了 进行更新
                            Collect collect = new Collect();
                            collect.setIs_collect(!isCollect);
                            collect.update(list.get(0).getObjectId(), new UpdateListener() {
                                @Override
                                public void done(BmobException e) {
                                    refreshCollectButton();
                                }
                            });
                        }else{
                            // 没有找到 说明之前没有收藏过
                            Collect collect = new Collect();
                            collect.setNew_id(newsID);
                            collect.setUser_id(userID);
                            collect.setIs_collect(!isCollect);
                            collect.save(new SaveListener<String>() {
                                @Override
                                public void done(String s, BmobException e) {
                                    refreshCollectButton();
                                }
                            });
                        }
                    }
                });

            }
        });
    }

    // 刷新界面中收藏按钮的文字
    private void refreshCollectButton() {
        isCollect = !isCollect;
        if(isCollect){
            btnCollect.setText("取消收藏");
        }else{
            btnCollect.setText("收藏");
        }
    }

    private void initCommentViews() {
        edtComment = findViewById(R.id.edt_comment);
        btnComment = findViewById(R.id.btn_comment);
        btnComment.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if(BmobUser.getCurrentUser() == null){
                    Intent intent = new Intent();
                    intent.setClass(ViewNewsActivity.this, LoginActivity.class);
                    startActivity(intent);
                }

                String content = edtComment.getText().toString();
                String userID = BmobUser.getCurrentUser().getObjectId();
                Comment comment = new Comment();
                comment.setNews_id(newsID);
                comment.setUser_id(userID);
                comment.setIs_del(false);
                comment.setContent(content);
                comment.save(new SaveListener<String>() {
                    @Override
                    public void done(String s, BmobException e) {
                        Log.e("ViewNewsActivity", "评论发表成功");
                        Toast.makeText(ViewNewsActivity.this,"评论发表成功",Toast.LENGTH_SHORT).show();
                    }
                });

            }
        });
    }


    private void initHandler() {
        handler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message message) {
                Log.e("MainAcitivity", "handleMessage");
                adapter.changData(mComments);
                return false;
            }
        });
    }
}
